package ${handlePackage};

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import ${voPackage}.ExResult;
import ${enumsPackage}.MessageEnum;
import ${exceptionPackage}.BusinessException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import javax.servlet.http.HttpServletRequest;

/**
 * @Name GlobalException
 * @Description 全局异常处理器
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ExResult> handleBusinessException(BusinessException ex, HttpServletRequest request) {
        log.error("【业务处理异常】：错误码={}，错误信息={}, 请求路径={}", ex.getCode(), ex.getMsg(), request.getRequestURI());
        return ResponseEntity.ok().body(ExResult.build(ex));
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity<ExResult> handleBindException(BindException ex, HttpServletRequest request) {
        log.error("【参数不合法异常】：错误信息={}，请求路径={}", request.getRequestURI());
        return getBindingResult(ex.getBindingResult());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ExResult> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
        log.error("【参数不合法异常】：错误信息={}，请求路径={}", request.getRequestURI());
        return getBindingResult(ex.getBindingResult());
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<ExResult> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex, HttpServletRequest request) {
        log.error("【参数不合法异常】：错误信息={}，请求路径={}", ex.getMessage(), request.getRequestURI());
        return ResponseEntity.ok().body(ExResult.build(MessageEnum.PARAMETER_VERIFICATION_ERROR));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ExResult> handleException(Exception ex, HttpServletRequest request) {
        log.error("【系统处理异常】：错误信息={}，请求路径={}", ex, request.getRequestURI());
        return ResponseEntity.ok().body(ExResult.build(MessageEnum.REQUEST_LIMITED));
    }

    /**
    * 参数不合法处理结果
    * */
    private ResponseEntity<ExResult> getBindingResult(BindingResult bindingResult) {
        StringBuilder sb = new StringBuilder();
        bindingResult.getAllErrors().forEach(t -> sb.append(t.getDefaultMessage()).append("；"));
        return ResponseEntity.ok().body(ExResult.build(MessageEnum.PARAMETER_VERIFICATION_ERROR).setMsg(sb.toString()));
    }
}
